﻿using AngleSharp.Html.Parser;
using PuppeteerSharp;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PuppeteerSharpSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //TestAsync().Wait();
            Test2Async().Wait();
        }

        private static async Task Test2Async()
        {
            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);

            var option = new LaunchOptions()
            {
                Headless = false
            };

            using (var browser = await Puppeteer.LaunchAsync(option))
            {
                using (var page = await browser.NewPageAsync())
                {
                    await page.GoToAsync("https://www.puppeteersharp.com/");
                    var html = await page.GetContentAsync();
                    var title = await page.GetTitleAsync();
                    await page.ScreenshotAsync($"f://{Guid.NewGuid().ToString("N")}.png");
                    await page.PdfAsync($"f://{Guid.NewGuid().ToString("N")}.pdf");
                }
            }
        }

        private async static Task TestAsync()
        {
            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);

            var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
            {
                Headless = true
            });

            var page = await browser.NewPageAsync();
            await page.GoToAsync("https://github.com/kblok/puppeteer-sharp");
            var html = await page.GetContentAsync();

            var parser = new HtmlParser();
            var doc = await parser.ParseDocumentAsync(html);
            var h2s = doc.QuerySelectorAll("h2");

            var strs = new List<string>();

            foreach (var h2 in h2s)
            {
                strs.Add(h2.TextContent);
            }
            var titleStr = string.Join(",", strs);
        }
    }
}
